package praktikumid.w10.p5;

import java.awt.Graphics;
import java.awt.Point;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
import java.util.List;

/**
 * Concrete shape - Polygon.
 * It has points, every point is connected
 * to the next point. The last one is connected
 * to the first one. 
 * <p>
 * During the drawing, the first and the last point
 * are not connected. They are connected after the shape
 * is finished, which takes place after double click.
 * @author Ago
 *
 */
public class Polygon extends Shape {

	/**
	 * Points of the polygon, which are connected
	 * by lines.
	 */
	List<Point> points = new ArrayList<Point>();
	
	@Override
	protected void paintComponent(Graphics g) {
		// let's connect every point (starting from the second)
		// to the previous point by line
		for (int i = 1; i < points.size(); i++) {
			g.drawLine(points.get(i).x, points.get(i).y,
					points.get(i - 1).x,
					points.get(i - 1).y);
		}
		if (isFinished) {
			// if the shape is finished,
			// connect the first and the last point
			g.drawLine(points.get(0).x, points.get(0).y,
					points.get(points.size() - 1).x,
					points.get(points.size() - 1).y);
			
		}
	}
	
	@Override
	public void mousePressed(MouseEvent e) {
		if (points.size() == 0) {
			// if there are no points, let's add
			points.add(e.getPoint());
		}
		// add a point, which we can move while dragging
		points.add(e.getPoint());
		if (e.getClickCount() > 1) {
			// with double click, end the shape
			isFinished = true;
		}
	}
	
	@Override
	public void mouseDragged(MouseEvent e) {
		// if we drag, let's change the location
		// of the last point
		points.get(points.size() - 1).setLocation(e.getPoint());
	}
	@Override
	public int getDistance(Point p) {
		// return the distance of the closest 
		// point from p.
		int minDistance = Integer.MAX_VALUE;
		for (Point p2 : points) {
			int d = (int) p2.distance(p);
			if (d < minDistance) {
				minDistance = d;
			}
		}
		return minDistance;
	}
	
	
	@Override
	public void move(int dx, int dy) {
		// moves every point of the polygon.
		for (Point p : points) {
			p.x += dx;
			p.y += dy;
		}
		
	}
}
